#include "Enroll.h"
#include "ui_Enroll.h"
#include "Client.h"
#include <QMessageBox>
#include <QBitmap>
#include <QStyleOption>
#include "mymessagebox.h"

Enroll::Enroll(Client *client, QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Enroll)
    , clientWindow(client)
    , socket(new QTcpSocket(this))  // 初始化 TCP socket
{
    ui->setupUi(this);

    // 隐藏原生标题栏
    setWindowFlags(Qt::FramelessWindowHint | Qt::Dialog);

    // 防止窗口背景透明
    setAttribute(Qt::WA_TranslucentBackground, false);

    ui->password->setEchoMode(QLineEdit::Password);
    ui->ensure->setEchoMode(QLineEdit::Password);

    // 连接服务器发送数据的槽
    connect(socket, &QTcpSocket::readyRead, this, &Enroll::onReadyRead);
}

Enroll::~Enroll()
{
    delete ui;
}

// 实现窗口拖动功能
void Enroll::mousePressEvent(QMouseEvent *event)
{
    // 检查是否点击了自定义标题栏
    if (event->button() == Qt::LeftButton && event->pos().y() <= 60) {
        m_isTitleBarClicked = true;
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    } else {
        m_isTitleBarClicked = false;
        // 让事件继续传播，确保其他控件能响应点击事件
        QWidget::mousePressEvent(event);
    }
}

void Enroll::mouseMoveEvent(QMouseEvent *event)
{
    // 只有在点击了标题栏之后才允许拖动
    if (m_isTitleBarClicked && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    } else {
        // 让事件继续传播，确保其他控件能响应移动事件
        QWidget::mouseMoveEvent(event);
    }
}

void Enroll::paintEvent(QPaintEvent *event)
{
    // 1. 绘制样式（QSS）
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); // 绘制样式

    // 2. 设置掩码，约定 painter 绘制区域
    QBitmap bmp(this->size());
    bmp.fill(Qt::white); // 填充 bitmap

    QPainter painter(&bmp);
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black); // 掩码值
    painter.drawRoundedRect(bmp.rect(), 30, 30); // 在 bitmap 中绘制圆角矩形

    // 设置掩码以确定本控件可绘制区域
    setMask(bmp);

    // 调用基类的 paintEvent
    QWidget::paintEvent(event);
}

void Enroll::on_returnButton_clicked()
{
    this->close();
    clientWindow->show();
}

void Enroll::on_yes_clicked()
{
    sendDataToServer();  // 点击按钮时发送数据到服务器
}

void Enroll::sendDataToServer()
{
    QString employeeId = ui->num->text();
    QString employeeName = ui->name->text();
    QString password = ui->password->text();
    QString ensurePassword = ui->ensure->text();

    // 检查输入是否完整
    if (employeeId.isEmpty() || employeeName.isEmpty() || password.isEmpty() || ensurePassword.isEmpty()) {
        // QMessageBox::warning(this, "错误", "请填写所有字段");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("请填写所有字段");
        msgBox.setButton("确定");
        msgBox.exec();
        return;
    }

    // 将工号和姓名拼接成一个字符串并发送到服务器
    QString dataToSend = QString("%1|%2|%3|%4").arg(employeeId).arg(employeeName).arg(password).arg(ensurePassword);
    socket->connectToHost("127.0.0.1", 12345);  // 连接服务器
    if (socket->waitForConnected(3000)) {  // 等待连接成功
        socket->write(dataToSend.toUtf8());  // 发送数据
    } else {
        // QMessageBox::warning(this, "错误", "无法连接到服务器");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("无法连接到服务器");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

void Enroll::onReadyRead()
{
    QByteArray data = socket->readAll();  // 读取服务器返回的数据
    QString response = QString::fromUtf8(data);

    handleServerResponse(response);  // 处理服务器响应
}

void Enroll::handleServerResponse(const QString &response)
{
    if (response == "ID_NAME_MISMATCH") {
        // QMessageBox::warning(this, "错误", "工号，姓名不匹配");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("工号，姓名不匹配");
        msgBox.setButton("确定");
        msgBox.exec();
    } else if (response == "ALREADY_REGISTERED") {
        // QMessageBox::warning(this, "错误", "该员工已认证");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("该员工已认证");
        msgBox.setButton("确定");
        msgBox.exec();
    } else if (response == "PASSWORD_MISMATCH") {
        // QMessageBox::warning(this, "错误", "密码，确认密码不同");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("密码，确认密码不同");
        msgBox.setButton("确定");
        msgBox.exec();
    } else if (response == "REGISTRATION_SUCCESS") {
        // QMessageBox::information(this, "成功", "员工认证成功");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("成功");
        msgBox.setText("员工认证成功");
        msgBox.setButton("确定");
        msgBox.exec();
        // 清空输入框
        ui->num->clear();
        ui->name->clear();
        ui->password->clear();
        ui->ensure->clear();
    } else {
        // QMessageBox::warning(this, "错误", "未知错误");
        MyMessageBox msgBox;
        msgBox.setWindowTitle("错误");
        msgBox.setText("未知错误");
        msgBox.setButton("确定");
        msgBox.exec();
    }
}

void Enroll::on_no_clicked()
{
    this->close();
    clientWindow->show();
}

